import time
import json
# import pandas as pd
import requests
import websocket

import time
import ssl
import pymongo
import base64
import re
import gzip
import hashlib

try:
    import thread
except ImportError:
    import _thread as thread


class websocket_clas():


    def __init__(self,feedId):
        unknow_key = "NTI3MTQ2NTA3MiRiY2E1ZWMyYS02ODUzLTQ5ZDAtYmI1My1jNzUxN2NmODZlODR"  # base64解码后 => 5271465072$bca5ec2a-6853-49d0-bb53-c7517cf86e84
        bytesStr = feedId.encode(encoding='utf-8')
        bytesStr.decode()
        b64str = base64.b64encode(bytesStr)
        b64str = b64str.decode("utf8", "ignore")
        self.SEND_DATA = "igkgCAH4AAok{}EAEiCWg1XzAuNC4xOCqPATUuMCAoTWFjaW50b3NoOyBJbnRlbCBNYWMgT1MgWCAxMF8xNF81KSBBcHBsZVdlYktpdC81MzcuMzYgKEtIVE1MLCBsaWtlIEdlY2tvKSBDaHJvbWUvNzcuMC4zODY1LjkwIFNhZmFyaS81MzcuMzYgTGliTWVzc2FnZUtpdFNkay8xNTcw{}CCTcyOTEzMjc3NEoAEAAKDnRiOTEwMDk5NV8yMDExAAA=".format(b64str, unknow_key)

    # GZIP解密
    def decode_gzip (self,base64_str):
        res = base64.b64decode(base64_str)
        res = gzip.decompress(res).decode('utf8',"ignore")
        return res

    # Base64解密
    def decode_base64 (self,base64_str):
        res = base64.b64decode(base64_str)
        return res

    def findNum (self,key, origin_str):
        res = re.findall('\"' + key + '\":(.*?)(,\"|})', origin_str)
        if len(res) > 0:
            return res
        else:
            return False

    def findStr (self,key, origin_str):
        res = re.findall('\"' + key + '\":\"(.*?)(\",\"|\"})', origin_str)
        if len(res) > 0:
            return res
        else:
            return False

    # 这里就是websocket爬虫的核心，发送请求，接收数据并做最后处理，
    def on_message(self,ws, message):
        res_dict = json.loads(message)

        # 判断 data 是否为空
        if res_dict['data'] == '':
            print('data为空')
            return
        print("{} - {}".format(res_dict['compressType'], res_dict['data']))

        if res_dict['compressType'] == 'COMMON':
            res_str = self.decode_base64(res_dict['data'])
            res_str = res_str.decode("utf8","ignore").strip().replace('\n','').replace('\n', '')
        else:
            res_str = self.decode_gzip(res_dict['data'])
            res_str = res_str.strip().replace('\n','').replace('\n', '')

        # cachedSize = findNum('cachedSize', res_str)
        # if cachedSize is not False:
        #     print('cachedSize：{}'.format(cachedSize[0][0]))

        onlineCount = self.findNum('onlineCount', res_str)
        if onlineCount is not False:
            print('onlineCount：{}'.format(onlineCount[0][0]))

        pageViewCount = self.findNum('pageViewCount', res_str)
        if pageViewCount is not False:
            print('pageViewCount：{}'.format(pageViewCount[0][0]))

        # serializedSize = findNum('serializedSize', res_str)
        # if serializedSize is not False:
        #     print('serializedSize：{}'.format(serializedSize[0][0]))

        totalCount = self.findNum('totalCount', res_str)
        if totalCount is not False:
            print('totalCount：{}'.format(totalCount[0][0]))


        userid = self.findNum('userid', res_str)
        if userid is not False:
            # fanLevel = findNum('fanLevel', res_str)
            nick = self.findNum('nick', res_str)
            print(userid[0:-1])
            print(nick[0:-1])

        print('----------------------------------------------------')

    def on_error(self, ws, error):
        print(error)

    # 关闭websocket长连接
    def on_close(self,ws):
        print("关闭连接")

    # 程序运行第一步
    @staticmethod
    def on_open(ws):
        my_send_data = websocket_clas.SEND_DATA
        print(my_send_data)
        # def run(*args):
        #     send_content = {
        #         "data": my_send_data,
        #         "dataId": "3504211_4409",
        #         "protocol": "ACCS_H5",
        #         "serviceId": "powermsg",
        #         "type": "REQ",
        #     }
        #     send_content = json.dumps(send_content)
        #     ws.send(send_content)
        #     print("thread terminating...")
        # thread.start_new_thread(run, ())

    def get_token(self,my_cookie):
        for i in range(3):
            try:
                url = 'https://acs.m.taobao.com/h5/mtop.mediaplatform.live.encryption/1.0/'

                headers = {
                    "Referer": "http://huodong.m.taobao.com/act/talent/live.html",
                    "Sec-Fetch-Mode": "no-cors",
                    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'
                }

                data = {"appKey": "H5_4282", "windowId": "2046630410_667"}
                data = str(data)
                APPKEY = '12574478'
                params = {
                    'AntiCreep': 'true',
                    'jsv': '2.5.0',
                    'appKey': APPKEY,
                    't': int(time.time() * 1000),
                    'sign': 'FAKE_SIGN_WITH_ANYTHING',
                    'api': 'mtop.mediaplatform.live.encryption',
                    'v': '1.0',
                    'type': 'json',
                    'dataType': 'json',
                    "sdkversion": "h5_1.3.7",
                    'callback': 'mtopjsonp3',
                    'data': data
                }
                headers['Cookie'] = my_cookie
                token_with_time = re.findall('_m_h5_tk=(.*?);', my_cookie)[0]
                token = token_with_time.split('_')[0]
                t2 = str(int(time.time() * 1000))
                c = '&'.join([token, t2, APPKEY, data])
                m = hashlib.md5()
                m.update(c.encode('utf-8'))
                params.update({'t': t2, 'sign': m.hexdigest()})

                r2 = requests.get(url, params=params, headers=headers)
                return json.loads(r2.text)
            except:
                continue



def main(feedid):
    # 获取 cookie
    myclient = pymongo.MongoClient("mongodb://47.98.146.210:27017")
    mydb_cookies = myclient["QK_GOODS"]
    mycol_cookies = mydb_cookies['qk_cookies']
    cookiee = mycol_cookies.find({}).sort([('_id', -1)]).limit(1)
    for cook in cookiee:
        my_cookie = cook['qk_taobao']

    header = {
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9,',
        'Cache-Control': 'no-cache',
        'Connection': 'Upgrade',
        'Cookie': my_cookie,
        'Host': 'acs.m.taobao.com:80',
        'Origin': 'https://taobaolive.taobao.com',
        'Pragma': 'no-cache',
        'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
        # 这个参数要进行实时修改
        'Sec-WebSocket-Key': 'WV9B4PXjzHvsFOaK4Vuzzg==',
        'Sec-WebSocket-Version': '13',
        'Upgrade': 'websocket',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'
    }

    websocket_cla = websocket_clas(feedid)

    # 获取 token
    res_token = websocket_cla.get_token(my_cookie)
    print(res_token)
    token = res_token['data']['result']
    print('直播token: {}'.format(token))

    websocket.enableTrace(True)
    url = "wss://acs.m.taobao.com:80/accs/auth?token={}".format(token)
    print(url)
    ws = websocket.WebSocketApp(url,
                                on_message=websocket_cla.on_message,
                                on_error=websocket_cla.on_error,
                                on_close=websocket_cla.on_close,
                                header=header)

    SEND_DATA = websocket_cla.SEND_DATA

    def include_function (ws):
        my_send_data = SEND_DATA
        print(my_send_data)
        def run(*args):
            send_content = {
                "data": my_send_data,
                "dataId": "3504211_4409",
                "protocol": "ACCS_H5",
                "serviceId": "powermsg",
                "type": "REQ",
            }
            send_content = json.dumps(send_content)
            ws.send(send_content)
            print("thread terminating...")
        thread.start_new_thread(run, ())

    ws.on_open = include_function

    # ws.on_open = websocket_cla.on_open
    ws.on_open = include_function
    ws.set
    ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})

if __name__ == '__main__':
    main('c1e97365-18b1-4d31-8b37-afa46fe8c44d')